package org.hdz.changelanguage;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;

import java.util.HashMap;
import java.util.Locale;

/**
 * Created by hdz on 2019/1/5.
 */

public class LanguageConfig {
    private static final int DEFAULT = 0;
    private static final int SIMPLIFIED_CHINESE = 1;
    private static final int TRADITIONAL_CHINESE = 2;
    private static final int ENGLISH = 3;
    private static final int JAPANESE = 4;

    public static HashMap<Integer, Locale> mAllLanguages = new HashMap<Integer, Locale>(8) {{
        put(ENGLISH,              Locale.ENGLISH);
        put(SIMPLIFIED_CHINESE,   Locale.SIMPLIFIED_CHINESE);
        put(TRADITIONAL_CHINESE,  Locale.TRADITIONAL_CHINESE);
        put(JAPANESE,             Locale.JAPANESE);
    }};

    public static void changeLanguage(Context context, int index) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();

        Locale locale = getLocaleByLanguage(index);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(locale);
        } else {
            config.locale = locale;
        }
        resources.updateConfiguration(config, dm);
    }


    public static Locale getLocaleByLanguage(int language) {
        if (isSupportLanguage(language)) {
            return mAllLanguages.get(language);
        } else {
            Locale locale = Locale.getDefault();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //解决了获取系统默认错误的问题
                locale = Resources.getSystem().getConfiguration().getLocales().get(0);
            }
            for (int key : mAllLanguages.keySet()) {
                if (mAllLanguages.get(key).getLanguage().equals(locale.getLanguage())) {
                    return locale;
                }
            }
        }
        return Locale.ENGLISH;
    }
    private static boolean isSupportLanguage(int language) {
        return mAllLanguages.containsKey(language);
    }
}
